package com.simpletour.qa.service.exception;


import com.simpletour.qa.common.http.ObjectRestResponse;
import com.simpletour.qa.common.http.ResponseCode;
import com.simpletour.qa.common.http.ResponseMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class CommonExceptionHandler {

    private final static Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ObjectRestResponse handleCommonException(Exception e){
        LOG.error("unknown exception.",e);
        return ObjectRestResponse.builder().code(ResponseCode.SERVER_INTERNAL_ERROR).msg(ResponseMsg.SERVER_INTERNAL_ERROR);
    }

    @ResponseBody
    @ExceptionHandler(EmptyResultDataAccessException.class)
    public ObjectRestResponse handleEmptyResultException(Exception e){
        LOG.error("empty result.",e);
        return ObjectRestResponse.builder().code(ResponseCode.RESOURCE_NOT_EXIST).msg(ResponseMsg.RESOURCE_NOT_EXIST);
    }


    @ResponseBody
    @ExceptionHandler(DataIntegrityViolationException.class)
    public ObjectRestResponse handleDataIntegrityViolationException(Exception e){
        LOG.error("break database constraint.",e);
        return ObjectRestResponse.builder().code(ResponseCode.PARAM_CHECK_ERROR).msg(ResponseMsg.PARAM_CHECK_ERROR);
    }



}
